from numpy import sqrt
from scipy import integrate


def gauss_legendre(f, start, end, n):
    """分为 n 段后, 利用五点 Gauss-Legendre 公式"""
    interval = (end - start) / n
    x = [0, sqrt(5 - 2 * sqrt(10 / 7)) / 3, -sqrt(5 - 2 * sqrt(10 / 7)) / 3, sqrt(5 + 2 * sqrt(10 / 7)) / 3,
         -sqrt(5 + 2 * sqrt(10 / 7)) / 3]
    w = [128 / 225, (322 + 13 * sqrt(70)) / 900, (322 + 13 * sqrt(70)) / 900, (322 - 13 * sqrt(70)) / 900,
         (322 - 13 * sqrt(70)) / 900]
    s = 0
    for i in range(n):
        for j in range(len(x)):
            s += w[j] * f(start + (2 * i + x[j] + 1) / 2 * interval) * interval / 2
    return s


def gauss_legendre_scipy(f, start, end, n1, n2):
    """分为 n1 段后, 利用 n2 点 Gauss-Legendre 公式"""
    interval = (end - start) / n1
    s = 0
    for i in range(n1):
        s += integrate.fixed_quad(f, start + i * interval, start + (i + 1) * interval, n=n2)[0]
    return s
